package com.atguigu.gmall.realtime.function;


import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.JdbcUtil;
import com.atguigu.gmall.realtime.util.RedisUtil;
import com.atguigu.gmall.realtime.util.ThreadPoolUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author lzc
 * @Date 2022/4/20 9:21
 */
public abstract class DimAsyncFunction<T> extends RichAsyncFunction<T, T> {
    
    private ThreadPoolExecutor threadPool;
    
    @Override
    public void open(Configuration parameters) throws Exception {
        threadPool = ThreadPoolUtil.getThreadPool();
        
    }
    
    protected abstract void addDIm(Jedis redisClient,
                                   Connection conn,
                                   T input,
                                   ResultFuture<T> resultFuture) throws Exception;
    
    @Override
    public void asyncInvoke(T input,   // 需要异步处理的数据
                            // 把异步处理后的结果放入到resultFuture
                            ResultFuture<T> resultFuture) throws Exception {
        
        threadPool.submit(new Runnable() {
            
            
            @Override
            public void run() {
                
                Connection conn = null;
                Jedis redisClient = null;
                // 多客户端
                try {
                    redisClient = RedisUtil.getRedisClient();
                    conn = JdbcUtil.getJdbcConnection(Constant.PHOENIX_DRIVER, Constant.PHOENIX_URL, null, null);
    
                    // 具体的维度补充, 父类是没有办法知道, 只能让子类去实现
                    addDIm(redisClient, conn, input, resultFuture);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (conn != null) {
                        try {
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    
                    if (redisClient != null) {
                        redisClient.close();
                    }
                }
                
            }
        });
        
        
    }
}
